package cn.moukou.tongji.ihealth.patient.service;

import cn.moukou.tongji.ihealth.patient.dao.DoctorMapper;
import cn.moukou.tongji.ihealth.patient.dao.PatientReserveMapper;
import cn.moukou.tongji.ihealth.patient.pojo.Doctor;
import cn.moukou.tongji.ihealth.patient.pojo.Patient;
import cn.moukou.tongji.ihealth.patient.pojo.PatientReserve;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PatientReserveService {

    @Autowired
    PatientReserveMapper reserveMapper;



    @Transactional
    public int insertOne(String pid, String patientName, int age, String sex, String phoneNumber, String desc,
                         Date date) {

        Map<String, Object> map = new HashMap<>();
        map.put("pid", pid);
        List<PatientReserve> reserves = reserveMapper.selectByMap(map);
        if(reserves.size()>0) {
            for(PatientReserve reserve : reserves) {
                if(reserve.getState()!=2) {
                    return -1;
                }
            }
        }

        PatientReserve reserve = new PatientReserve();
        reserve.setPid(pid);
        reserve.setPatientName(patientName);
        reserve.setPatientAge(age);
        reserve.setPatientSex(sex);
        reserve.setPatientPhoneNumber(phoneNumber);
        reserve.setPatientDescription(desc);
        reserve.setDate(date);
        reserve.setDid("");
        return reserveMapper.insert(reserve);
    }

    public PatientReserve getOne(Long id) {
        return reserveMapper.selectById(id);
    }

    public int deleteOne(Long id) {
        return reserveMapper.deleteById(id);
    }

    public List<PatientReserve> getMyReserves(String pid) {
        Map<String, Object> map = new HashMap<>();
        map.put("pid", pid);
        List<PatientReserve> reserves = reserveMapper.selectByMap(map);
        for(PatientReserve reserve : reserves) {
            reserve.setIdstr(reserve.getId().toString());
        }
        return reserves;
    }


    public int updateState() {
        java.util.Date date = new java.util.Date();
        Date sqlDate = new Date(date.getTime());
        QueryWrapper<PatientReserve> wrapper = new QueryWrapper();
        wrapper.le("date", sqlDate);
        List<PatientReserve> reserves = reserveMapper.selectList(wrapper);
        for (PatientReserve reserve : reserves) {
            reserve.setState(2);
            reserveMapper.updateById(reserve);
        }
        return reserves.size();
    }

}
